package com.guodi.model.controller;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guodi.common.utils.UuidUtil;
import com.guodi.core.boot.ctrl.BaseController;
import com.guodi.core.tool.api.R;
import com.guodi.model.entity.DiagnosisProblemScene;
import com.guodi.model.service.IDiagnosisProblemSceneService;
import com.guodi.model.utils.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @描述：诊断分析-问题场景管理表控制类
 * @作者: 徐金洲
 * @日期: 2023-05-05
 */
@RestController
@RequestMapping("/DiagnosisProblemScene")
@Api(value = "API - DiagnosisProblemSceneController", tags = "问题场景管理表控制类")
public class DiagnosisProblemSceneController extends BaseController {

    @Resource
    public IDiagnosisProblemSceneService diagnosisProblemSceneService;

    /**
     * @描述: 分页查询列表
     * @入参: DiagnosisProblemScene
     * @出参: page
     * @作者: 徐金洲
     * @日期: 2023-05-05
     **/
    @PostMapping("/list")
    @ApiOperation(value = "分页查询列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "页数", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "查询数量", required = true, dataType = "int", paramType = "query")
    })
    public R list(Page page, DiagnosisProblemScene diagnosisProblemScene) {
        page = diagnosisProblemSceneService.listByEntity(page, diagnosisProblemScene);
        return R.data(page);
    }


    /**
     * @描述: 新增诊断分析-问题场景管理信息
     * @入参: DiagnosisProblemScene
     * @出参: boolean
     * @作者: 徐金洲
     * @日期: 2023-05-05
     **/
    @PostMapping("/save")
    @ApiOperation(value = "新增")
    public R save(@Valid DiagnosisProblemScene diagnosisProblemScene) {
        prepareData(diagnosisProblemScene,true);
        diagnosisProblemScene.setId(UuidUtil.get32UUID());
        boolean temp = diagnosisProblemSceneService.save(diagnosisProblemScene);
        if (temp) {
            return R.success("新增成功");
        }
        return R.fail("新增失败");
    }


    /**
     * @描述: 修改诊断分析-问题场景管理信息
     * @入参: DiagnosisProblemScene
     * @出参: boolean
     * @作者: 徐金洲
     * @日期: 2023-05-05
     **/
    @PostMapping("/update")
    @ApiOperation(value = "修改")
    public R update(@Valid DiagnosisProblemScene diagnosisProblemScene) throws IOException {
        prepareData(diagnosisProblemScene, false);
        if (diagnosisProblemSceneService.saveOrUpdate(diagnosisProblemScene)) {
            return R.success("修改成功");
        }
        return R.fail("修改失败");
    }


    /**
     * @描述: 删除诊断分析-问题场景管理信息
     * @入参: DiagnosisProblemScene
     * @出参: boolean
     * @作者: 徐金洲
     * @日期: 2023-05-05
     **/
    @PostMapping("/delete")
    @ApiOperation(value = "删除")
    @ApiImplicitParam(name = "ids", value = "主键id，如果多个，英文逗号隔开", required = true, dataType = "string", paramType = "query")
    public R delete(String ids) {
        if (StringUtils.isBlank(ids)) {
            return R.fail("id不能为空!");
        }
        //将英文逗号分隔的字符串 id 转成 list
        List<String> idList = Arrays.asList(ids.trim().split(","));
        if (idList.size() > 0) {
            //删除问题场景管理信息
            boolean temp = diagnosisProblemSceneService.removeByIds(idList);
            if (temp) {
                return R.success("删除成功!");
            }
        }
        return R.fail("删除失败!");
    }


    /**
     * @描述: 导出诊断分析-问题场景管理信息
     * @入参: DiagnosisProblemScene
     * @出参: boolean
     * @作者: 徐金洲
     * @日期: 2023-05-05
     **/
    @PostMapping("/exportExcel")
    @ApiOperation(value = "导出问题场景管理信息Excel")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "exportType", value = "导出类型,传入all默认导出全部,否则根据,分隔导出", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "ids", value = "导出问题场景管理信息id集合", required = false, dataType = "string", paramType = "query")
    })
    public void exportExcel(String exportType, String ids) {
        List<DiagnosisProblemScene> list;
        //查询问题场景管理信息
        if ("all".equals(exportType)) {
            // 导出所有的问题场景管理信息
            LambdaQueryWrapper<DiagnosisProblemScene> queryWrapper = new QueryWrapper().lambda();
            queryWrapper.orderByAsc(DiagnosisProblemScene::getCreateTime);
            list = diagnosisProblemSceneService.list(queryWrapper);
        } else {
            List<String> idsList = Arrays.asList(ids.split(","));
            // 导出选中的问题场景管理信息
            LambdaQueryWrapper<DiagnosisProblemScene> queryWrapper = new QueryWrapper().lambda();
            queryWrapper.orderByAsc(DiagnosisProblemScene::getCreateTime);
            queryWrapper.in(DiagnosisProblemScene::getId, idsList);
            list = diagnosisProblemSceneService.list(queryWrapper);
        }

        String relatedIndicators = "";
        String idtName = "";
        for(DiagnosisProblemScene diagnosisProblemScene : list){
            relatedIndicators = diagnosisProblemScene.getRelatedIndicators();
            //具体因素字段处理
            JSONArray array = JSONArray.parseArray(relatedIndicators);
            for(int i = 0; i < array.size(); i++){
                idtName  += (String) array.getJSONObject(i).get("idtName") + ",";;
            }
            //去掉拼接的最后一个逗号
            idtName = idtName.substring(0,idtName.length()-1);
            //重新赋值
            diagnosisProblemScene.setRelatedIndicators(idtName);
            //清空 idtName
            idtName = "";
        }

        List<Object[]> dataList = new ArrayList<Object[]>();
        for (int i = 0; i < list.size(); i++) {
            DiagnosisProblemScene diagnosisProblemScene = list.get(i);
            Object[] datas = new Object[5];
            datas[0] = diagnosisProblemScene.getProblemNum();
            datas[1] = diagnosisProblemScene.getProblemName();
            datas[2] = diagnosisProblemScene.getDescribe();
            datas[3] = diagnosisProblemScene.getInfluenceFactor();
            datas[4] = diagnosisProblemScene.getRelatedIndicators();
            dataList.add(datas);
        }
        // 导出Excel
        String[] titles = {"问题编号", "问题名称", "问题描述", "影响因素","具体因素"};
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        ExcelUtil.exportExcel(response, "问题场景管理", "问题场景管理", titles, dataList);
    }


    private void prepareData(DiagnosisProblemScene diagnosisProblemScene, boolean isSave) {
        if(isSave){
            //diagnosisProblemScene.setCreator(this.getUser().getUserId().toString());
            diagnosisProblemScene.setCreateTime(new Date());
            //防止误修改
            diagnosisProblemScene.setModifier(null);
            diagnosisProblemScene.setModifyTime(null);
        }else{
            diagnosisProblemScene.setModifier(this.getUser().getUserId().toString());
            diagnosisProblemScene.setModifyTime(new Date());
            //防止误修改
            diagnosisProblemScene.setCreator(null);
            diagnosisProblemScene.setCreateTime(null);
        }
    }


}
